package cn.wqb.cloudar.utils;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;

import java.awt.image.BufferedImage;

/**
 * 依赖I:/JavaWeb/javacv-1.5.2.jar
 */
public class VideoUtils {

    /**
	 *截取视频帧
	 */
    public static byte[] fetchFrame(String videoUrl) {
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber("I:/PHPProjects/风之谷.mp4");
        try {
            ff.start();
            // 截取中间帧图片(具体依实际情况而定)

            int i = 0;
            int totalFrames = ff.getLengthInFrames();
            int fetchFrame = Math.min(30, totalFrames);//截取第30帧
            Frame frame = null;
            while (i < totalFrames) {
                frame = ff.grabFrame();
                if (frame != null && i == fetchFrame) {
                    // 截取的帧图片
                    Java2DFrameConverter converter = new Java2DFrameConverter();
                    BufferedImage srcImage = converter.getBufferedImage(frame);
                    int srcImageWidth = srcImage.getWidth();
                    int srcImageHeight = srcImage.getHeight();
                    // 对截图进行等比例缩放(缩略图)
                    int width = 480;
                    int height = (int) (((double) width / srcImageWidth) * srcImageHeight);
                    BufferedImage thumbnailImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
                    byte[] bytes = ImageUtils.bufferedImageToBytes(thumbnailImage);
                    ff.stop();
                    return bytes;
                }
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
